#!/bin/sh

. /usr/local/certificate-services/environment 

apt-get install apache2 openssl

/usr/sbin/a2enmod ssl
# get a server certificate and install it
cd $EJBCA_HOME 

./bin/ejbca.sh ra adduser webserver foo123 'CN=smartcard20.demo,O=Smartcard 2.0' NULL ServerCA NULL 1 P12 CP_SSLServer EEP_SSLServer
./bin/ejbca.sh ra setclearpwd webserver foo123
./bin/ejbca.sh batch

./bin/ejbca.sh ca getrootcert eIDCA /etc/apache2/ca-clients.crt

openssl pkcs12 -info -in $EJBCA_HOME/p12/webserver.p12 -nodes  -nocerts -passin pass:foo123  > /etc/apache2/server.key
openssl pkcs12 -info -in $EJBCA_HOME/p12/webserver.p12 -nokeys -clcerts -passin pass:foo123  > /etc/apache2/server.crt
openssl pkcs12 -info -in $EJBCA_HOME/p12/webserver.p12 -nokeys -cacerts -passin pass:foo123 >> /etc/apache2/ca-clients.crt
openssl pkcs12 -info -in $EJBCA_HOME/p12/webserver.p12 -nokeys -cacerts -passin pass:foo123  > /etc/apache2/CertificateChain.crt

./bin/ejbca.sh ca getcrl ServerCA /tmp/ca.crl
openssl crl -inform der -outform pem -in /tmp/ca.crl -out /etc/apache2/ca.crl

# copy in configured apache sites
cp ${HTMF_HOME}/src/inst/smartcard20/vhost-ssl /etc/apache2/sites-available/smartcard20-ssl
cp ${HTMF_HOME}/src/inst/smartcard20/vhost-http /etc/apache2/sites-available/smartcard20-http

# replace path
perl -pi -e "s#/usr/local/htmf#${HTMF_HOME}#gio" /etc/apache2/sites-available/smartcard20-ssl
perl -pi -e "s#/usr/local/htmf#${HTMF_HOME}#gio" /etc/apache2/sites-available/smartcard20-http
perl -pi -e "s/#AddHandler\ cgi-script\ \.cgi/AddHandler cgi-script .cgi/gio" /etc/apache2/apache2.conf


chmod +x ${HTMF_HOME}/src/inst/smartcard20/www/test-your-certificate.cgi


# disable old sites 
ensites=`(cd /etc/apache2/sites-enabled/ ; ls )`
/usr/sbin/a2dissite ${ensites}

/usr/sbin/a2ensite smartcard20-ssl
/usr/sbin/a2ensite smartcard20-http

/etc/init.d/apache2 restart
